package com.dianrui.operation.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.event.RefreshFix;
import com.dianrui.operation.event.RefreshRepair;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.GlideUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.ninegride.NineView;
import com.dianrui.operation.view.ninegride.RatioImageView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RepairOrderInfoActivity extends BaseActivity implements NineView.NineViewShowCallBack, AMapLocationListener {
    private List<String> imageList = new ArrayList<>();
    private String maintainId, lat, lng;
    private String status;
    private String title;
    private String mDegree;
    private String carNumber;
    private String mFormName;
    private String typeTag = "";//1，故障，2，入库，3报废
    private boolean isFirstLoc = true;
    private Double lats;
    private Double lngs;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;

    @BindView(R.id.title)
    TextView titles;
    @BindView(R.id.order_code)
    TextView orderCode;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.remark)
    TextView remark;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.update_time)
    TextView updateTime;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.remove_trouble)
    Button remove_trouble;//解除故障
    @BindView(R.id.report)
    Button report;//申报
    @BindView(R.id.scrap_btn)
    Button scrapBtn;//报废
    @BindView(R.id.nine)
    NineView nine;

    @Override
    public int getContentViewId() {
        return R.layout.repair_order_info;
    }

    @Override
    public void initView() {
        titles.setText("工单详情");
        if (getIntent() != null && getIntent().getExtras() != null) {
            maintainId = getIntent().getStringExtra("maintain_id");
            lat = getIntent().getStringExtra("lat");
            lng = getIntent().getStringExtra("lng");
            status = getIntent().getStringExtra("status");
            title = getIntent().getStringExtra("title");
            carNumber = getIntent().getStringExtra("number");
            typeTag = getIntent().getStringExtra("typeTag");
            mDegree = getIntent().getStringExtra("degree");
            mFormName = getIntent().getStringExtra("form_name");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(RepairOrderInfoActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(RepairOrderInfoActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }


        //判断degree，0（申报入库、解除故障），1（报废，解除故障），2（无操作）
        switch (mDegree) {
            case "0":
                report.setVisibility(View.VISIBLE);
                remove_trouble.setVisibility(View.VISIBLE);
                break;
            case "1":
                scrapBtn.setVisibility(View.VISIBLE);
                remove_trouble.setVisibility(View.VISIBLE);
                break;
            case "2":
                remove_trouble.setVisibility(View.GONE);
                report.setVisibility(View.GONE);
                scrapBtn.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        topRight.setText("地图查看");
        topRight.setVisibility(View.VISIBLE);
        getRepairInfo();
        nine.maxCount(9).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);

    }

    private void getRepairInfo() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("maintain_id", maintainId);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.REPAIR_INFO, jsonObject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                orderCode.setText(jsonObject.optJSONObject("data").optString("order_code"));
                                number.setText(jsonObject.optJSONObject("data").optString("number"));
                                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("form_name"))) {
                                    name.setText("无");
                                } else {
                                    name.setText(jsonObject.optJSONObject("data").optString("form_name"));
                                }
                                remark.setText(jsonObject.optJSONObject("data").optString("contents"));
                                time.setText(jsonObject.optJSONObject("data").optString("create_time"));
                                if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("update_time"))) {
                                    updateTime.setText("暂无");
                                } else {
                                    updateTime.setText(jsonObject.optJSONObject("data").optString("update_time"));
                                }
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("photo");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        String str = jsonArray.optString(i);
                                        imageList.add(str);
                                    }
                                    nine.urlList(imageList);
                                    nine.setVisibility(View.VISIBLE);
                                } else {
                                    nine.setVisibility(View.GONE);
                                }

                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SharedUtil.setToken("");
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void initData() {}


    @OnClick({R.id.back, R.id.top_right, R.id.copy, R.id.remove_trouble, R.id.report, R.id.scrap_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.top_right:
                Intent intent = new Intent(RepairOrderInfoActivity.this, ShowLocationsActivity.class);
                intent.putExtra("degree", mDegree);
                intent.putExtra("lat", lat);
                intent.putExtra("lng", lng);
                intent.putExtra("title", title);
                intent.putExtra("formname", mFormName);
                intent.putExtra("number", carNumber);
                startActivity(intent);
                break;


            case R.id.copy:
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                ClipData clipData = ClipData.newPlainText(null, number.getText().toString());
                // 把数据集设置（复制）到剪贴板
                if (clipboard != null) {
                    clipboard.setPrimaryClip(clipData);
                }
                Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
                break;
            case R.id.remove_trouble://解除故障
                fixOperation("2");
                break;

            case R.id.report://申报
                fixOperation("3");
                break;

            case R.id.scrap_btn://报废
                fixOperation("4");
                break;

            default:
                break;
        }
    }

    //各个按钮状态传参
    private void fixOperation(String type) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("maintain_id", maintainId);
        jsonObject.addProperty("type", type);//操作类型：type，2已完成（解除故障），3需要入库；4，车辆报废
        jsonObject.addProperty("gps", lngs + "," + lats);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() +Url.FIXOPERTAION, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    EventBus.getDefault().post(new RefreshRepair());
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    finish();
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });


    }

    //按完成
    private void confirm() {
       showLoadingDialog("请稍候...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("maintain_id", maintainId);
        jsonObject.addProperty("lng", lng);
        jsonObject.addProperty("lat", lat);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.REPAIR_CONFIGRM, jsonObject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                EventBus.getDefault().post(new RefreshRepair());
                                EventBus.getDefault().post(new RefreshFix());
                                ToastUtil.showToast(jsonObject.optString("message"));
                                finish();
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SharedUtil.setToken("");
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, RepairOrderInfoActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, RepairOrderInfoActivity.this));
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        List<String> temp = new ArrayList<>();
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                temp.add(imageList.get(i));
            } else {
                count++;
            }
        }
        startActivity(new Intent(RepairOrderInfoActivity.this, BigImageActivity.class)
                .putStringArrayListExtra("data", (ArrayList<String>) temp)
                .putExtra("current", position));
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {

    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (isFirstLoc) {
            lats = aMapLocation.getLatitude();
            lngs = aMapLocation.getLongitude();
            isFirstLoc = false;
        }
    }
}
